package com.chooseCourses.servlet.admin;

import com.chooseCourses.dao.BaseDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@WebServlet("/ScheduleAdd")
public class ScheduleAdd extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().append("Served at: ").append(req.getContextPath());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String courseName = req.getParameter("courseName");//传过来的是一个id值
        String time = req.getParameter("time");
        String room = req.getParameter("room");
        int teacherId = Integer.parseInt(req.getParameter("teacherId"));
        int id = Integer.parseInt(req.getParameter("Id"));
        String userName = req.getParameter("userName");//为空？
        String userId = req.getParameter("userId");
        System.out.println("SA"+userName+userId);


        // 创建数据库操作对象
        BaseDao baseDao = new BaseDao();
        PreparedStatement ps = null;// 创建ps对象

        // 调用db中的方法
        // 添加数据
        try {
            String sql = "select id from course where name = '" + courseName+"'";
            ResultSet resultSet = baseDao.getConnection().prepareStatement(sql).executeQuery();
            int courseId = 0;
            resultSet.next();
            courseId=resultSet.getInt("id");


            //实现插入数据
            sql = "insert into schedule(id,courseId,teacherid,room,name,time) values(?,?,?,?,?,?)";

            ps = baseDao.getConnection().prepareStatement(sql);

            ps.setInt(1, id);
            ps.setInt(2, courseId);
            ps.setInt(3, teacherId);
            ps.setString(4, room);
            ps.setString(5, courseName);
            ps.setString(6, time);
            ps.executeUpdate();// 执行sql语句

            baseDao.closeResource(null,ps,null);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        resp.sendRedirect("admin/scheduleMes.jsp?userName=" + userName + "&userId=" + userId);
        doGet(req, resp);
    }

    public ScheduleAdd() {
        super();
    }
}
